package com.tenthoundsqps.service;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Elasticsearch服务类
 * 提供订单相关的全文搜索功能
 * 
 * 搜索策略：
 * 1. 先通过ES搜索获取订单ID列表
 * 2. 再通过批量查询获取订单详情
 * 
 * 支持的搜索类型：
 * 1. 手机号精确搜索
 * 2. 商户名称模糊搜索
 * 3. 订单号精确搜索
 */
@Service
public class ElasticsearchService {
    
    private static final Logger logger = LoggerFactory.getLogger(ElasticsearchService.class);
    
    /**
     * Elasticsearch高级客户端
     * 用于执行搜索请求
     * 
     * 注意：RestHighLevelClient 在 Elasticsearch 7.15+ 中已被弃用，
     * 但在当前版本中仍可使用。建议在升级到 Elasticsearch 8.0+ 时
     * 迁移到新的 Java API Client。
     */
    @Autowired
    private RestHighLevelClient elasticsearchClient;
    
    // 订单索引名称
    private static final String ORDER_INDEX = "orders";
    
    /**
     * 根据手机号搜索订单ID列表
     * 使用TermQuery进行精确匹配
     * 
     * @param phone 手机号
     * @param limit 限制返回结果数量
     * @return 订单ID列表
     */
    public List<Long> searchOrdersByPhone(String phone, int limit) {
        List<Long> orderIds = new ArrayList<>();
        try {
            // 创建搜索请求
            SearchRequest searchRequest = new SearchRequest(ORDER_INDEX);
            // 构建搜索条件
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            // 精确匹配手机号
            searchSourceBuilder.query(QueryBuilders.termQuery("phoneNumber", phone));
            // 限制返回结果数量
            searchSourceBuilder.size(limit);
            searchRequest.source(searchSourceBuilder);
            
            // 执行搜索
            SearchResponse searchResponse = elasticsearchClient.search(searchRequest, RequestOptions.DEFAULT);
            
            // 解析搜索结果
            searchResponse.getHits().forEach(hit -> {
                // 将文档ID转换为订单ID
                Long orderId = Long.valueOf(hit.getId());
                orderIds.add(orderId);
            });
            
        } catch (IOException e) {
            logger.error("Error searching orders by phone: {}", phone, e);
        }
        
        return orderIds;
    }
    
    /**
     * 根据商户名称搜索订单ID列表
     * 使用MatchQuery进行全文匹配
     * 
     * @param merchantName 商户名称
     * @param limit 限制返回结果数量
     * @return 订单ID列表
     */
    public List<Long> searchOrdersByMerchantName(String merchantName, int limit) {
        List<Long> orderIds = new ArrayList<>();
        try {
            // 创建搜索请求
            SearchRequest searchRequest = new SearchRequest(ORDER_INDEX);
            // 构建搜索条件
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            // 全文匹配商户名称
            searchSourceBuilder.query(QueryBuilders.matchQuery("merchantName", merchantName));
            // 限制返回结果数量
            searchSourceBuilder.size(limit);
            searchRequest.source(searchSourceBuilder);
            
            // 执行搜索
            SearchResponse searchResponse = elasticsearchClient.search(searchRequest, RequestOptions.DEFAULT);
            
            // 解析搜索结果
            searchResponse.getHits().forEach(hit -> {
                // 将文档ID转换为订单ID
                Long orderId = Long.valueOf(hit.getId());
                orderIds.add(orderId);
            });
            
        } catch (IOException e) {
            logger.error("Error searching orders by merchant name: {}", merchantName, e);
        }
        
        return orderIds;
    }
    
    /**
     * 根据订单号搜索订单ID
     * 使用TermQuery进行精确匹配
     * 
     * @param orderNo 订单号
     * @return 订单ID
     */
    public Long searchOrderByOrderNo(String orderNo) {
        try {
            // 创建搜索请求
            SearchRequest searchRequest = new SearchRequest(ORDER_INDEX);
            // 构建搜索条件
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            // 精确匹配订单号
            searchSourceBuilder.query(QueryBuilders.termQuery("orderNo", orderNo));
            // 只需要一条结果
            searchSourceBuilder.size(1);
            searchRequest.source(searchSourceBuilder);
            
            // 执行搜索
            SearchResponse searchResponse = elasticsearchClient.search(searchRequest, RequestOptions.DEFAULT);
            
            // 解析搜索结果
            if (searchResponse.getHits().getHits().length > 0) {
                // 返回第一个匹配结果的订单ID
                return Long.valueOf(searchResponse.getHits().getHits()[0].getId());
            }
            
        } catch (IOException e) {
            logger.error("Error searching order by orderNo: {}", orderNo, e);
        }
        
        return null;
    }
}